// mircoApp/horizon/useDevice/useDevice.js
const app = getApp();
var buleHandle = require("../../../utils/horizonBule");
Page({
  behaviors: [buleHandle],
  /**
   * 页面的初始数据
   */
  data: {
    connected: false,
    time: '',
    runing: false,
    strength: 1,
    reenter: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {

    if (options.mac) {
      this.setData({
        macAddress: options.mac
      })
      let post = await this.connectMachine_Post(options);
      console.log(this.data.setting, post, 'postssssssssssssssssssssss')
      if (post) {
        wx.showModal({
          title: "",
          content: "当前没有开机次数",
          success: (res) => {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.redirectTo({
                url: `/packageB/member/category/search_v2/search_v2?machine_id=${this.data.setting.id}&tag=horizon`,
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
              wx.navigateBack({
                delta: 1,
              })
            }
          }
        })
        return
      } else {
        wx.openBluetoothAdapter({
          success: (res) => {
            console.log(options.reenter)
            if (options.reenter == '1') {
              // 已经连接回到设备页面
              this.setData({
                reenter: true,
                connected: true,
              })
              wx.offBLECharacteristicValueChange();
              this.getBLEDeviceCharacteristics(options.dId, options.sId, 'checkStatus');
            } else {
              this.startBluetoothDevicesDiscovery();
            }
          }
        })
      }

    }
  },
  strToArrayBuffer(str) {
    var buffer = new ArrayBuffer(str.length / 2);
    var uint8Array = new Uint8Array(buffer);
    for (var i = 0; i < str.length; i += 2) {
      var byteValue = parseInt(str.substr(i, 2), 16);
      uint8Array[i / 2] = byteValue;
    }
    return buffer;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (!this.data.runing && this.data.deviceId) {
      console.log("没有运行设备就离开控制页面需要断开蓝牙连接", this.data.deviceId)
      this.sendOpenOption('53544f50');
    }
    this.stopBluetoothDevicesDiscovery()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  connectMachine_Post(options) {
    return new Promise((resolve, reject) => {
      let urlStr = app.getNetAddresss("plugin.horizon.frontend.machine-use.connectMachine");
      app._postNetWork({
        url: urlStr,
        data: {
          code: this.data.macAddress
        },
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            this.setData({
              setting: res.data
            })
            if (res.data.count == 0) {
              if(options.reenter == '1'){
                // 如果是已经连接了的设备不验证次数
                resolve(false)
                return
              }
              resolve(true)
            } else {
              resolve(false)
            }
            console.log(this.data.setting, res.data, 'connectMachine_Post')
          } else {
            app.tips(res.msg)
            reject(false)
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    })
  },
  ToBuySearch() {
    wx.navigateTo({
      url: `/packageB/member/category/search_v2/search_v2?machine_id=${this.data.setting.id}&tag=horizon`,
    })
  },
  startBtn() {
    if (!this.data.connected) {
      console.log('已经断开连接，重新连接')
      wx.showModal({
        title: '提示',
        content: '是否重新连接设备：' + this.data.macAddress,
        complete: (res) => {
          if (res.confirm) {
            this.startBluetoothDevicesDiscovery();
          }
        }
      })
      return
    }
    if (!this.data.time && !this.data.reenter) {
      wx.showToast({
        title: '请先设置时长',
      })
      return
    }
    if (!this.data.modelKey) {
      wx.showToast({
        title: '请先设置模式',
      })
      return
    }
    this.serveStart();
  },
  serveStart() {
    let urlStr = app.getNetAddresss("plugin.horizon.frontend.machine-use.startMachine");
    app._getNetWork({
      url: urlStr,
      data: {
        code: this.data.macAddress,
        min: this.data.time
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res)
          this.sendOpenOption('53544152');
          // 查询状态 一分钟自动返回
          this.sendOpenOption('53544154');
          // 设备开启请求服务端记录
        } else {
          app.tips(res.msg)
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  serveEnd() {
    let urlStr = app.getNetAddresss("plugin.horizon.frontend.machine-use.stopMachine");
    app._getNetWork({
      url: urlStr,
      data: {
        code: this.data.macAddress,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res)
        } else {
          app.tips(res.msg)
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  deviceStop() {
    //53 54 4F 50
    this.sendOpenOption('53544f50');
    if (this.data.reenter) {
      // 已经连接的设备id，用于断开连接
      this.setData({
        deviceId: this.options.dId
      })
    }
    wx.showLoading({
      title: '设备停止中',
    })
    // 请求服务端结束
    this.serveEnd();
  },
  // 字符串转16进制字符串
  string2Hex(str) {
    let minutes = str;
    let hexValue = minutes.toString(16).padStart(2, '0').toUpperCase();
    return hexValue
  },
  changeTotal(e) {
    let val = e.detail;
    this.sendOpenOption(`4C4556${this.string2Hex(Number(val))}`);
    this.checkStatus();
  },
  inpblur(e) {
    let {
      value
    } = e.detail;
    if (value > 60) {
      app.tips('最大时间为60分钟');
      this.setData({
        time: 60
      })
      return
    }
    this.sendOpenOption(`544953${this.string2Hex(Number(value))}`);
  },
  setModel(e) {
    if (!this.data.connected) {
      app.tips('未连接设备')
      return
    }
    let {
      key
    } = e.currentTarget.dataset;
    if (key == 's') {
      this.sendOpenOption('4D730000');
    } else if (key == 'a') {
      this.sendOpenOption('4D610000')
    } else if (key == 'i') {
      this.sendOpenOption('4D690000')
    }
    if(this.data.runing){
      if (this.data.setting.has_one_machine_type.min_modal > 1) {
        console.log(this.data.setting.has_one_machine_type.min_modal, '开启了最小强度')
        this.sendOpenOption(`4C4556${this.string2Hex(Number(this.data.setting.has_one_machine_type.min_modal))}`);
      }
    }
    this.setData({
      modelKey: key,
      strength: this.data.setting.has_one_machine_type.min_modal
    })
  }
})